﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using DukeNUS.FacilitiesPlanning.FPSystem;
using DukeNUS.FacilitiesPlanning.FPSystem.Data;
using DukeNUS.FacilitiesPlanning.FPSystem.Models;
using System.Diagnostics;

namespace DukeNUS.FacilitiesPlanning.FPSystem.Controllers
{
    public class LogoutController : Controller
    {
        
        public ActionResult Index()
        {
            if (Session[ApplicationSessionKeys.CurrentUser] != null)
            {
                if (Session[ApplicationSessionKeys.CurrentUser].GetType() == typeof(ApplicationUser))
                {
                    var currentUser = (ApplicationUser)Session[ApplicationSessionKeys.CurrentUser];
                    if (currentUser.IsLoggedIn)
                    {
                        try
                        {
                            using (DukeNUSDatabase db = new DukeNUSDatabase())
                            {
                                using (TransactionScope trans = new TransactionScope())
                                {
                                    db.LogActivities.Add(new LogActivity()
                                    {
                                        Action = ApplicationActions.Logout,
                                        UserID  = currentUser.User.UserID
                                    });

                                    db.SaveChanges(); trans.Complete(); Session.Clear();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            EventLog.WriteEntry(GetType().FullName, string.Format("Message: {0}\nStack Trace: {1}", ex.Message, ex.StackTrace), EventLogEntryType.Error);
                        }
                    }
                }
            }

            return Redirect("~");
        }

    }
}
